//
//  HTTPManger.m
//  HTTPManger
//
//  Created by Lee on 10/2/13.
//  Copyright (c) 2013 Lee. All rights reserved.
//

#import "HTTPManger.h"
@implementation HTTPMangerModel

@end
@implementation HTTPManger
static HTTPManger *manger;
+(id)shareHTTPManger
{
    @synchronized(self){
        if (!manger) {
            manger = [[HTTPManger alloc] init];
        }
    }
    return manger;
}
- (id)init{
    if (self = [super init])
    {
        NSLog(@"初始化.....");
        dataArr = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return self;
}
-(void)addURL:(NSString *)url  completion:(void (^)(ManagerModelState,ASIHTTPRequest *))completion
{
    //completion参数名，调用后会执行语句块
    
    //HTTPMangerModel自定义的对象，含有ASIHTTPRequest和与之对应的completion
    HTTPMangerModel *model = [[HTTPMangerModel alloc] init];
    model.completionHandler = completion;
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
    
    model.request = request;
    model.request.delegate = self;
    model.request.timeOutSeconds = 20.0f;
    [model.request startAsynchronous];
    [dataArr addObject:model];
    
    [model release];

}
#pragma mark - ASIHTTPRequestDelegate
- (void)requestStarted:(ASIHTTPRequest *)request
{
    //遍历取对象
    for(HTTPMangerModel *model in dataArr)
    {
        if ([model.request isEqual:request])
        {
           
            //语句块会执行
            model.completionHandler(ManagerModelStateStarted,request);
            break;
        }
        NSLog(@"请求开始");
        
    }
    

}
- (void)requestFinished:(ASIHTTPRequest *)request
{
    for(HTTPMangerModel *model in dataArr)
    {
        if ([model.request isEqual:request])
        {
           
            model.completionHandler(ManagerModelStateFinished,request);
            [dataArr removeObject:model];
            break;
        }
        NSLog(@"结束");
    }

}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    for(HTTPMangerModel *model in dataArr)
    {
        if ([model.request isEqual:request])
        {
            model.completionHandler(ManagerModelStateFailed,request);
            //使用完后remove掉。
            [dataArr removeObject:model];
            break;
        }
        NSLog(@"请求失败");
        
    }

}
@end
